package com.weilx959.spt.app.controller;

import com.weilx959.spt.app.SqlParserApplication;
import com.weilx959.spt.app.context.ConfigContext;
import com.weilx959.spt.app.context.PluginContext;
import com.weilx959.spt.app.model.AppConfig;
import com.weilx959.spt.app.utils.ResourceBundleUtil;
import com.weilx959.spt.app.utils.StylesheetUtil;
import com.weilx959.spt.core.LanguageContext;
import com.weilx959.spt.core.component.ComboBoxFormItemControl;
import com.weilx959.spt.core.component.VDialog;
import com.weilx959.spt.core.config.Config;
import com.weilx959.spt.core.config.FormControlConfig;
import com.weilx959.spt.core.constants.CommonConstants;
import com.weilx959.spt.core.constants.LanguageEnum;
import com.weilx959.spt.core.constants.ThemeEnum;
import javafx.fxml.FXML;
import javafx.scene.control.ListCell;
import lombok.extern.slf4j.Slf4j;

import java.util.*;

@Slf4j
public class GeneralConfigFormController {
    @FXML
    private FormControlConfig generalConfig;

    @FXML
    private ComboBoxFormItemControl<ThemeEnum> themeItem;

    @FXML
    private ComboBoxFormItemControl<LanguageEnum> languageItem;

    private ResourceBundle bundle;

    public Config getConfig() {
        return generalConfig;
    }

    @FXML
    private void initialize() {
        bundle = ResourceBundleUtil.get();
        this.initValue();
        this.bingEvent();
    }

    /**
     * 初始化值
     */
    private void initValue() {
        themeItem.setValue(Optional.ofNullable(ConfigContext.get())
            .map(AppConfig::getGeneral)
            .map(AppConfig.General::getTheme)
            .orElse(CommonConstants.DEFAULT_THEME));
        languageItem.getValueControl().setCellFactory(listView -> new LanguageListCell());
        languageItem.getValueControl().setButtonCell(new LanguageListCell());
        languageItem.setValue(Optional.ofNullable(LanguageContext.get()).orElse(CommonConstants.DEFAULT_LANGUAGE));
        generalConfig.submit(); // 手动修改值后提交一次，重置默认值
    }

    /**
     * 绑定事件
     */
    private void bingEvent() {
        themeItem.valueProperty().addListener((observable, oldValue, newValue) -> {
            log.info("Theme change! The old one is {}, and new one is {}", oldValue, newValue);
            if (Objects.isNull(newValue) || newValue.equals(oldValue)) {
                return;
            }
            // 新主题 & 添加插件的样式文件
            final List<String> stylesheets = new ArrayList<>();
            Optional.of(newValue).map(ThemeEnum::getStyle).ifPresent(stylesheets::add);
            PluginContext.getAll().forEach((id, plugin) -> Optional.ofNullable(plugin)
                .map(p -> p.getStylesheets(newValue))
                .ifPresent(stylesheets::addAll));
            StylesheetUtil.addStylesheets(stylesheets, newValue);
        });
        languageItem.valueProperty().addListener(((observable, oldValue, newValue) -> {
            log.info("Language change! The old one is {}, and new one is {}", oldValue, newValue);
            if (Objects.isNull(newValue) || newValue.equals(LanguageContext.get())) {
                return;
            }
            VDialog.confirm(bundle.getString("app.config.general.language.confirm") + newValue.name(), dialog -> {
                dialog.close();
                // 保存配置
                LanguageContext.set(newValue);
                // 重启
                SqlParserApplication.restart();
            }, dialog -> {
                dialog.close();
                // 恢复默认值
                languageItem.reset();
            });
        }));
    }

    private static class LanguageListCell extends ListCell<LanguageEnum> {
        @Override
        protected void updateItem(LanguageEnum item, boolean empty) {
            super.updateItem(item, empty);

            if (empty || item == null) {
                super.setText(null);
                return;
            }
            super.setText(item.getName());
        }
    }
}
